import 'package:dio/dio.dart';
import 'package:get/get.dart' as GetResponse;

import '../../../ui/pages/login/login.dart';
import '../../constants/sp_key.dart';
import '../../model/base/api_result_data.dart';
import '../../model/login_model.dart';
import '../sp_utils.dart';

class TokenInterceptor extends QueuedInterceptorsWrapper {
  final Dio dio;
  final Dio tokenDio;

  TokenInterceptor({required this.dio, required this.tokenDio});

  @override
  void onError(DioException err, ErrorInterceptorHandler handler) async {
    if (err.response?.statusCode == 401) {
      ApiResultData apiResultData =
          ApiResultData.fromJson(err.response?.data, (data) {});
      if (apiResultData.status == 4001) {
        GetResponse.Get.offAllNamed(LoginScreen.routeName);
        return handler.next(err);
      }
      String newToken = await getNewToken();
      if (newToken.isEmpty) {
        return handler.next(err);
      }
      final opts = err.requestOptions;
      opts.headers['Authorization'] = 'Bearer $newToken';
      final cloneReq = await dio.fetch(opts);
      return handler.resolve(cloneReq);
    }
    return handler.next(err);
  }

  Future<String> getNewToken() async {
    String newToken = "";
    try {
      String token = await SPUtils.get(keyToken) ?? "";
      String refreshToken = await SPUtils.get(keyRefreshToken) ?? "";
      var param = {"token": token, "refreshToken": refreshToken};
      Response response =
          await tokenDio.post("/api/users/refreshToken", data: param);
      ApiResultData<LoginModel> apiResultData =
          ApiResultData<LoginModel>.fromJson(
              response.data, LoginModel.fromJson);
      if (apiResultData.status == 2000) {
        newToken = apiResultData.data?.token ?? "";
        SPUtils.set(keyToken, newToken);
        SPUtils.set(keyRefreshToken, apiResultData.data?.refreshToken);
      } else if (apiResultData.status == 5500) {
        GetResponse.Get.toNamed(LoginScreen.routeName);
      }
    } catch (e) {
      print(e);
    }
    return newToken;
  }
}
